package com.kvest.fortests.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;
import com.kvest.fortests.LoggerService;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 08.05.13
 * Time: 21:40
 * To change this template use File | Settings | File Templates.
 */
public class RepeatedService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();

        //LoggerService.getInstance().writeLog("create RepeatedService");
        Log.d("KVEST_TAG", "create RepeatedService");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.d("KVEST_TAG", "destroy RepeatedService");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LoggerService.getInstance().writeLog("start RepeatedService");
        logBatteryStatus();

        work();

        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void work() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException interruptedException) {

                }

                Log.d("KVEST_TAG", "work finished");
                restartSelf();
                stopSelf();
            }
        }).start();
    }

    private void restartSelf() {
        LoggerService.getInstance().writeLog("restartSelf");
        AlarmManager am = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(getApplicationContext(), RepeatedService.class);
        PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, intent, 0);

        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60 * 1000, pi);
    }

    private void logBatteryStatus() {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        float batteryPct = level / (float)scale;
        LoggerService.getInstance().writeLog("level=" + level + " scale=" + scale + " batteryPct=" + batteryPct);
    }
}
